package pro.softzhang.algo.lc600;

import pro.softzhang.algo.flag.knowledge.KSlidingWindow;

/**
 *
 */
@KSlidingWindow(KSlidingWindow.WindowType.FIXED_LENGTH)
public class LC643_MaximumAverageSubarrayI {
    public static void main(String[] args) {
//        int[] ints = {0,4,0,3,2};
//        System.out.println(new Solution().findMaxAverage(ints, 1));
        int[] arr = {-1};
        int k = 1;
        System.out.println(new Solution1().findMaxAverage(arr, k));
    }


    /**
     * 两个循环，一个窗口，一个窗口内求和，窗口内最大值，窗口内最大值/k
     */
    static
    class Solution {
        public double findMaxAverage(int[] nums, int k) {
            int maxSum = 0;
            for(int i = 0; i < k; i++) {
                maxSum += nums[i];
            }

            int windowSum = maxSum;
            for(int i = k; i < nums.length; i++) {
                windowSum = windowSum - nums[i - k] + nums[i];
                maxSum = Math.max(windowSum, maxSum);
            }
            return (double)maxSum / k;
        }
    }

    /**
     * 合一块写法
     */
    static
    class Solution1 {
        public double findMaxAverage(int[] nums, int k) {
            int maxSum = Integer.MIN_VALUE, windowSum = 0;
            for(int i = 0; i < nums.length; i++) {
                // 进窗
                windowSum += nums[i];

                // 一直到窗口大小
                if (i < k - 1) {
                    continue;
                }

                // 更新
                maxSum = Math.max(maxSum, windowSum);

                // 出窗
                windowSum = windowSum - nums[i - k + 1];
            }
            return (double) maxSum / k;
        }
    }
}
